package cn.com.tbshuda.fastdfsthreadlocal.fast;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.StorageClient1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: wsd
 * @date: 2021/4/27 9:34
 */
@Service
public class FileClientImpl implements FileClient{
    @Autowired
    private FdfsByPorperties fdfsByPorperties;
    @Override
    public Map uploadFile(File file) {
        byte[] buff = getFileBuff(file);
        String file_ext_name =  getFileExtName(file.getName());
        return send(buff, file_ext_name, null);
    }


    @Override
    public Map uploadFile(File file, String file_ext_name) {
        byte[] buff = getFileBuff(file);
        return send(buff,file_ext_name,null);
    }


    @Override
    public Map uploadFile(byte[] buff,String file_ext_name) {
        return send(buff,file_ext_name,null);
    }

    //上传缓存数据到storage服务器
    private Map send(byte[] buff, String file_ext_name, NameValuePair[] mate_list){
        String upPath = null;
        Map<String, Object> resuleMap = new HashMap<>();

        StorageClient1 storageClient1 = null;
        ConnectionPool pool = ConnectionPool.getConnectionPool();
        storageClient1 = pool.checkout(10);
        try {
            upPath = storageClient1.upload_file1(buff, file_ext_name, mate_list);
            pool.checkin(storageClient1);
            resuleMap.put("upPath", upPath);
            resuleMap.put("123123", fdfsByPorperties);
            resuleMap.put("attPath", "http://"+storageClient1.getTrackerServer().getInetSocketAddress().getHostName()
            +":"+fdfsByPorperties.getHttp_tracker_http_port()+"/"+upPath);
        } catch (IOException e) {
            //如果出现了IO异常应该销毁此连接
            pool.drop(storageClient1);
            e.printStackTrace();
        } catch (Exception e) {
            pool.drop(storageClient1);
            e.printStackTrace();
        }

        return resuleMap;
    }

    //将文件缓存到字节数组中
    private byte[] getFileBuff(File file){
        byte[] buff = null;
        try {
            FileInputStream inputStream = new FileInputStream(file);
            buff = new byte[inputStream.available()];
            inputStream.read(buff);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buff;
    }

    //通过文件名称获取文件扩展名
    private String getFileExtName(String name){
        String ext_name = null;
        if(name != null){
            if(name.contains(".")){
                ext_name = name.substring(name.indexOf(".")+1);
            }
        }
        return ext_name;
    }
}
